package cc.wsyw126.java.nowcoder.sword_offer;

import java.util.ArrayList;
import java.util.LinkedList;

/**
 * Created by Administrator on 2017/4/17.
 * 和为S的连续正数序列
 */
public class FindContinuousSequence {
    public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) {
        LinkedList<Integer> process = new LinkedList<>();
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        if (sum <= 2) return result;
        int count = 0;
        for (int i = 1; i <= (1 + sum) / 2; i++) {
            process.add(i);
            count += i;
            if (count >= sum) {
                while (count > sum) {
                    Integer remove = process.remove();
                    count -= remove;
                }
                if (count == sum) {
                    ArrayList<Integer> integers = new ArrayList<>();
                    for (Integer proces : process) {
                        integers.add(proces);
                    }
                    result.add(integers);
                    Integer remove = process.remove();
                    count -= remove;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        FindContinuousSequence findContinuousSequence = new FindContinuousSequence();
        ArrayList<ArrayList<Integer>> arrayLists = findContinuousSequence.FindContinuousSequence(9);
        for (ArrayList<Integer> arrayList : arrayLists) {
            for (Integer integer : arrayList) {
                System.out.print(integer + "\t");
            }
            System.out.println();
        }
    }
}
